<template>
  <v-container fluid class="record-wrapper">
    <v-layout row nowrap justify-center>

      <v-flex md8 sm10 xs12>
        <v-layout row wrap justify-center>
        <v-layout row wrap justify-center>
          <v-flex xs6 style="margin-top: 20px;">
            <h1 class="date-title text-xs-left font-style">{{todayText}} {{week}}</h1>
          </v-flex>
          <v-flex xs6 style="margin-top: 20px;">
            <h1 class="date-title text-xs-right font-style">{{$route.query.name}}</h1>
          </v-flex>
        </v-layout>
          <v-flex xs12 d-flex justify-center>
            <div class="tab-wrapper">
              <div v-for="item of tabItems" :key="item.name" :class="{'tab-item': true, 'tab-selected': item.value === selected}" @click="tabChange(item.value)">
                <span class="tab-title">{{item.name}}</span>
                <div class="tab-content">
                </div>
              </div>
            </div>
          </v-flex>

          <v-flex xs12 class="tab-border elevation-1" v-show="selected == 1">
            <v-flex xs12 class="mb-2 mt-3">
              <v-layout row align-center justify-end>
                <v-spacer></v-spacer>
                  <v-flex xs2 class="text-xs-right">
                    <v-btn @click="$router.push(`/demanddetails?type=add&department=${$route.query.type}`)" dark color="cyan darken-2">
                      <v-icon>add</v-icon>
                      <span class="pl-2 subheading">新增需求</span>
                    </v-btn>
                  </v-flex>
                  <v-flex xs1>
                    <v-btn @click="$router.push('/demand?select=2')" dark color="blue">
                      <v-icon>arrow_back</v-icon>
                      <span class="pl-2 subheading">返回</span>
                    </v-btn>
                  </v-flex>
              </v-layout>
            </v-flex>
            <v-data-table :loading="showProgress" :headers="uheaders" :items="unfinishedData" hide-actions >
              <v-progress-linear slot="progress" color="success" height="5" indeterminate></v-progress-linear>
              <template slot="items" slot-scope="props">
                <td class="text-xs-center subheading" width="13%">{{ props.item.demandRecord.demandName }}</td>
                <td class="text-xs-center subheading" width="12%">{{ props.item.project  }}</td>
                <td class="text-xs-center subheading" width="10%">{{ props.item.areaName }}</td>
                <td class="text-xs-center subheading" width="12%">{{ getTime(props.item.ddRecord.createTime, 'date') }}</td>
                <td class="text-xs-center subheading" width="12%">{{ getTime(props.item.ddRecord.deadTime, 'date') }}</td>
                <td class="text-xs-center subheading" width="10%">
                  <v-avatar size="16" :color="statusColor[props.item.ddRecord.status]"></v-avatar>
                  <span class="status-td">{{ props.item.ddRecord.status | Status }}</span>
                </td>
                <td class="text-xs-center subheading" width="10%">{{ props.item.unfinished | UnfinishedStatus }}</td>
                <td class="text-xs-center" width="21%">
                  <v-btn flat round dark color="green" class="mx-1" @click="edit(props.item)">
                    <span class="mx-1">编辑</span>
                    <v-icon color="green">edit</v-icon>
                  </v-btn>
                  <v-btn flat round dark color="red" class="mx-1" @click="del(props.item)">
                    <span class="mx-1">删除</span>
                    <v-icon color="red">delete_forever</v-icon>
                  </v-btn>
                </td>
              </template>
              <!-- 没有数据时显示的提示 -->
              <template slot="no-data">
                <div class="text-xs-center">
                  <v-icon color="yellow darken-3">warning</v-icon>
                  <span class="subheading">暂无数据</span>
                </div>
              </template>
            </v-data-table>
            <div class="text-xs-center my-2">
              <v-pagination @input="uPageChange" circle :length="upagination.pageCount" :total-visible="upagination.totalVisible" v-model="upagination.page"></v-pagination>
            </div>
          </v-flex>

          <v-flex xs12 class="tab-border elevation-1" v-show="selected == 2">
            <v-layout xs12 wrap row justify-center>
              <v-flex xs12  class="mb-2 mt-3">
                <v-layout row justify-start class="pl-2 pr-4">
                  <v-flex xs3 class="mx-1">
                    <v-text-field hide-details name="demandName" label="需求名称" v-model="queryForm.demandName"></v-text-field>
                  </v-flex>
                  <v-flex xs3 class="mx-1">
                    <v-select hide-details :items="projects_area" v-model="queryForm.projectName" label="所属项目"></v-select>
                  </v-flex>
                   <v-btn flat icon @click="clearConditions" dark color="cyan">
                      <v-icon>refresh</v-icon>
                    </v-btn>
                  <v-flex xs1>
                    <v-btn @click="search" dark color="cyan darken-2">
                      <v-icon>search</v-icon>
                      <span class="pl-2 subheading">查询</span>
                    </v-btn>
                  </v-flex>
                  <v-flex xs1>
                    <v-btn @click="$router.push('/demand?select=2')" dark color="blue">
                      <v-icon>arrow_back</v-icon>
                      <span class="pl-2 subheading">返回</span>
                    </v-btn>
                  </v-flex>
                </v-layout>
              </v-flex>

            </v-layout>
            <v-data-table :loading="showProgress" :headers="fheaders" :items="finishedData" hide-actions>
              <v-progress-linear slot="progress" color="success" height="5" indeterminate></v-progress-linear>
              <template slot="items" slot-scope="props">
                <td class="text-xs-center subheading" width="14%">{{ props.item.demandRecord.demandName }}</td>
                <td class="text-xs-center subheading" width="12%">{{ props.item.project}}</td>
                <td class="text-xs-center subheading" width="9%">{{ props.item.areaName }}</td>
                <td class="text-xs-center subheading" width="11%">{{ getTime(props.item.demandRecord.createTime, 'date') }}</td>
                <td class="text-xs-center subheading" width="11%">{{ getTime(props.item.ddRecord.finishTime, 'date') }}</td>
                <td class="text-xs-center subheading" width="7%">{{ props.item.versionRecord.director }}</td>
                <td class="text-xs-center" width="21%">
                  <v-btn flat round dark color="green" class="mx-1" @click="details(props.item)">
                    <span class="mx-1">详情</span>
                    <v-icon color="green">more</v-icon>
                  </v-btn>
                  <v-btn flat round dark color="red" class="mx-1" @click="del(props.item)">
                    <span class="mx-1">删除</span>
                    <v-icon color="red">delete_forever</v-icon>
                  </v-btn>
                </td>
              </template>
              <!-- 没有数据时显示的提示 -->
              <template slot="no-data">
                <div class="text-xs-center">
                  <v-icon color="yellow darken-3">warning</v-icon>
                  <span class="subheading">暂无数据</span>
                </div>
              </template>
            </v-data-table>
            <div class="text-xs-center my-2">
              <v-pagination @input="fPageChange" circle :length="fpagination.pageCount" :total-visible="fpagination.totalVisible" v-model="fpagination.page"></v-pagination>
            </div>
          </v-flex>

        </v-layout>
      </v-flex>
    </v-layout>
    <v-dialog v-model="modal" persistent max-width="290">
      <v-card>
        <v-card-title class="headline">注意!</v-card-title>
        <v-card-text class="title">{{modalText}}</v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="red darken-1" flat @click.native="modal = false">取消</v-btn>
          <v-btn color="green darken-1" flat @click.native="confirmModal">确认</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<script>
import * as demand from "../../api/demand";
import { getTime, getToday } from "../../util";
import { mapState } from 'vuex'

// import PROJECT from '../../util/projects'
let PROJECT = {};
export default {
  data: () => ({
    tabs: null,
    showProgress: false,
    dialog: false,
    modal: false,
    date: "",
     todayText: getToday(),
     weekdays: [
      "星期日",
      "星期一",
      "星期二",
      "星期三",
      "星期四",
      "星期五",
      "星期六"
    ],
    week: "",
    modalText: "确认删除该条需求吗？",
    projectName: 1,
    departmentName: 1,
    projectItems: [],
    flimit: 10,
    foffset: 0,
    queryForm: {},
    fpagination: {
      page: 1,
      pageCount: 1,
      totalVisible: 7
    },
    ulimit: 10,
    uoffset: 0,
    upagination: {
      page: 1,
      pageCount: 1,
      totalVisible: 7
    },
    selected: 1,
    tabItems: [
      {
        name: "未完成",
        value: 1
      },
      {
        name: "已完成",
        value: 2
      }
    ],
    delItem: null,
    queryForm: {},
    isSearch: false,
    unfinishedData: [],
    finishedData: [],
    showProgress: false,
    statusColor: {
      "0": "amber",
      "1": "green",
      "2": "indigo",
      "3": "red"
    },
    projTypesItems: {
      "0": "无",
      "1": "客户端",
      "2": "服务端"
    },
    uheaders: [
      {
        text: "需求名称",
        value: "projName",
        align: "center",
        sortable: false
      },
      {
        text: "项目名称",
        value: "releaseTime",
        align: "center",
        sortable: false
      },
      {
        text: "公众号",
        value: "version",
        align: "center",
        sortable: false
      },
      {
        text: "提交日期",
        value: "version",
        align: "center",
        sortable: false
      },
      {
        text: "完成日期",
        value: "vleader",
        align: "center",
        sortable: false
      },
      {
        text: "需求状态",
        value: "status",
        align: "center",
        sortable: false
      },
      {
        text: "状态详情",
        value: "status",
        align: "center",
        sortable: false
      },
      {
        text: "操作",
        value: "actions",
        align: "center",
        sortable: false
      }
    ],
    fheaders: [
      {
        text: "需求名称",
        value: "projName",
        align: "center",
        sortable: false
      },
      {
        text: "项目名称",
        value: "releaseTime",
        align: "center",
        sortable: false
      },
      {
        text: "公众号",
        value: "version",
        align: "center",
        sortable: false
      },
      {
        text: "需求提交日期",
        value: "version",
        align: "center",
        sortable: false
      },
      {
        text: "版本提交日期",
        value: "vleader",
        align: "center",
        sortable: false
      },
      {
        text: "版本负责人",
        value: "status",
        align: "center",
        sortable: false
      },
      {
        text: "操作",
        value: "actions",
        align: "center",
        sortable: false
      }
    ],
    dayData: {},
    weekdays: [
      "星期日",
      "星期一",
      "星期二",
      "星期三",
      "星期四",
      "星期五",
      "星期六"
    ],
    week: "",
    department: 1,
    projectList: {},
    tabItems: [
      {
        name: "未完成",
        value: 1
      },
      {
        name: "已完成",
        value: 2
      }
    ],
    PROJECT: {},
    DEPARTMENT: {},
    projects_area: []
  }),
  computed: {
    ...mapState(['state_projects','state_departments'])
  },
  mounted() {
    this.department = +this.$route.query.type;
    // this.initialize();
    let day = new Date();

    this.week = this.weekdays[day.getDay()];
    this.getProjectList()
    this.$nextTick(()=>{
        _.forEach(this.state_projects, (item, i)=>{
        this.PROJECT[item.value] = item.text
        })
      _.forEach(this.state_departments, (item, i)=>{
      this.DEPARTMENT[item.value] = item.text
    })
  })
    _.forEach(this.state_projects, (item, i)=>{
        this.PROJECT[item.value] = item.text
        })
      _.forEach(this.state_departments, (item, i)=>{
      this.DEPARTMENT[item.value] = item.text
    })
    this.getFinished()
    this.getUnfinished()

  },
  beforeUpdate() {

  },
  watch: {
    // 监测路由参数变化
    $route(to, from) {
      console.log(to.params.gametype);
    }
  },
  filters: {
     UnfinishedStatus(val) {
      switch (val) {
        case 0:
          return "即将到期";
        case 1:
          return "任务延期";
        case 2:
          return "正常任务";
        case 3:
          return "回滚任务";
        default:
          return "未知";
      }
    },
    Status(val) {
      switch (val) {
        case 0:
          return "老版本";
        case 1:
          return "运行中";
        case 2:
          return "已回滚";
        case 3:
          return "未完成";
        default:
          return "未知状态";
      }
    },
    ProjName: function(val) {
      return PROJECT[val];
    },
    DpName: function(val) {
      return DEPARTMENT[val];
    }
  },
  methods: {
    getTime,
    initialize() {
      this.tableData = [
        {
          demandName: "声音",
          createTime: "2018/6/19 10:32:26",
          deadTime: "2018/6/19 16:32:26",
          projectName: 1,
          status: 1
        },
        {
          demandName: "实时在线人数",
          createTime: "2018/6/19 12:42:06",
          deadTime: "2018/6/19 12:42:06",
          projectName: 6,
          status: 2
        }
      ];
    },
    getProjectList() {
      demand.getProjectList.r().then(({ data }) => {
        console.error(data);
        let d = data.data;
        if (data.result == 0) {
          let projects = [];
          _.forEach(d.dataList, (item, i)=>{
            projects.push({
              text: item.projectName + '-' + this.projTypesItems[item.type]+ '-' + item.area.areaName,
              value: item.id
            })
          })

          this.projects_area = projects;
        }
      });
    },
    getUnfinished() {
      let opt = {
        offset: this.uoffset,
        limit: this.ulimit,
        type: 1,
        department: this.department
      };
      demand.getDemandListDP.r(opt).then(({ data }) => {
        if (data.result == 0) {
          this.unfinishedData = data.data.dataList;
          let datalist = data.data.dataList
          let today = new Date().getTime()
          _.forEach(datalist, (item, i)=>{
              item.unfinished = (item.ddRecord.deadTime  - today) < (24*60*60*1000*2) ?  0 : 2
              if(item.ddRecord.deadTime  < today) {
                item.unfinished = 1
              }
              if(item.ddRecord.status == 2) {
                item.unfinished = 3
              }
          })
          this.upagination.pageCount = data.data.totalCount
            ? Math.ceil(data.data.totalCount / this.ulimit)
            : 1;
        } else {
        }
      });
    },
    getFinished() {
      let opt = {
        offset: this.foffset,
        limit: this.flimit,
        type: 2,
        department: this.department
      };
      demand.getDemandListDP.r(opt).then(({ data }) => {
        if (data.result == 0) {
          console.error(data)
          this.finishedData = data.data.dataList;
          this.fpagination.pageCount = data.data.totalCount
            ? Math.ceil(data.data.totalCount / this.flimit)
            : 1;
        } else {
        }
      });
    },
    delDemand() {
      let opt = {
        id: this.delItem.demandRecord.id
      };
      demand.delDemand.r(opt).then(({ data }) => {
        $Vue.$emit("toggleSnackbar", {
          text: data.message
        });
        if (data.result == 0) {
          this.getUnfinished()
          this.getFinished()

        } else {
        }
          this.modal = false;

      });
    },
    searchFinished(form){
      demand.searchFinished.r(form).then(({ data }) => {
        if (data.result == 0) {
          this.tableData = data.data.dataList;
          this.pagination.pageCount = data.data.totalCount
            ? Math.ceil(data.data.totalCount / this.limit)
            : 1;
        } else {
        }
      });
    },
    edit(item) {
      // let date = getTime(item.releaseTime).split(' ')[0]
      this.$router.push(
        `/demanddetails?type=edit&demandid=${item.demandRecord.id}&department=${
          this.$route.query.type
        }&handover=${this.$route.query.handover}`
      );
    },
    details(item) {
      // let date = getTime(item.releaseTime).split(' ')[0]
      this.$router.push(
        `/demanddetails?type=details&demandid=${item.demandRecord.id}&department=${
          this.$route.query.type
        }&from=finished`
      );
    },
    del(item) {
      this.delItem = item;
      this.modal = true;
      // this.delDemand();
    },
    confirmModal() {
      this.delDemand()
    },
    uPageChange(page) {
      this.uoffset = (page - 1) * this.ulimit;
      this.getUnfinished();
    },
    fPageChange(page) {
      this.foffset = (page - 1) * this.flimit;
      this.getFinished();
    },
    tabChange(value) {
      this.selected = value
      // this.getDemandList();
    },
    search(fromPage) {
      let valid = 0;
      let form = {};
      _.forEach(this.queryForm, (item, key) => {
         form[key] = item ;
         valid += 1;
      });
      if (valid == 0) {
        alert("请至少选择一个查询条件")
      }
      // 点击分页
      if (fromPage !== "wyvj") {
        this.offset = 0;
        this.pagination.page = 1;
      }
      form.limit = this.limit;
      form.offset = this.offset;
      this.searchFinished(form)
      this.isSearch = true;
    },
    clearConditions() {
      this.queryForm = {}
      this.getFinished();
    }
  },
};
</script>

<style lang="less" scoped>
.date-title {
  font-size: 2.5rem;
  font-weight: 400;
  padding: 0 0.5rem;
}
.tab-border {
  border: 1px solid #ddd;
  background: #fafafa;
  padding: 0 5px;
}
</style>


